import { login } from '@/api/user'
import router from '@/router/index'
import { ElLoading, ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouterStore } from './router'
import { useCookies } from '@vueuse/integrations/useCookies'
import { useStorage } from '@vueuse/core'

import { useAppStore } from '@/pinia'

export const useUserStore = defineStore(
  'user',
  () => {
    const appStore = useAppStore()
    const loadingInstance = ref(null)
    const userInfo = ref({
      // uuid: '',
      // nickName: '',
      // headerImg: '',
      authority: { defaultRouter: '' }
    })

    const token = useStorage('token', '')
    const currentToken = computed(() => token.value || '')

    const setUserInfo = (val) => {
      userInfo.value = val
      if(val.front==2){
        userInfo.value.authority = { defaultRouter: 'dashboard' }
      }else{
        userInfo.value.authority = { defaultRouter: 'home' }
      }
      localStorage.setItem('userInfo',JSON.stringify(userInfo.value))
    }

    const setToken = (val) => {
      token.value = val
    }

    const NeedInit = async () => {
      await ClearStorage()
      await router.push({ name: 'Init', replace: true })
    }

    const ResetUserInfo = (value = {}) => {
      userInfo.value = {
        ...userInfo.value,
        ...value
      }
    }
    /* 登录*/
    const LoginIn = async (loginInfo) => {
      try {
        loadingInstance.value = ElLoading.service({
          fullscreen: true,
          text: '登录中，请稍候...'
        })
        const res = await login(loginInfo)
        // if (res.code !== 0) {
        //   ElMessage.error(res.message || '登录失败')
        //   return false
        // }
        // // 登陆成功，设置用户信息和权限相关信息
        setUserInfo(res.result.user)
        setToken(res.result.token)

        // // 初始化路由信息
        const routerStore = useRouterStore()
        await routerStore.SetAsyncRouter()
        const asyncRouters = routerStore.asyncRouters

        // 注册到路由表里
        asyncRouters.forEach((asyncRouter) => {
          router.addRoute(asyncRouter)
        })

          //if(res.result.user.front==2){
            let name = ''
            if(asyncRouters[0].children[0].children.length==0){
               name = asyncRouters[0].children[0].name
            }else if(asyncRouters[0].children[0].children[0].children.length==0){
              name = asyncRouters[0].children[0].children[0].name
            }else{
              name = asyncRouters[0].children[0].children[0].children[0].name
            }
            await router.replace({ name: name})
            localStorage.setItem('crj',name)
            routerStore.setLeftMenu(asyncRouters[0].children[0].name)
          //}else{
            
            // await router.replace({ name: 'home' })
            // routerStore.setLeftMenu('home')
          //}
        // 全部操作均结束，关闭loading并返回
        return true
      } catch (error) {
        console.error('LoginIn error:', error)
        return false
      } finally {
        loadingInstance.value?.close()
      }
    }
    /* 登出*/
    const LoginOut = async () => {
      await ClearStorage()
      // 把路由定向到登录页，无需等待直接reload
      router.push({ name: 'Login', replace: true })
      window.location.reload()
    }
    /* 清理数据 */
    const ClearStorage = async () => {
      token.value = ''
      sessionStorage.clear()
      localStorage.removeItem('originSetting')
    }
    return {
      userInfo,
      token: currentToken,
      NeedInit,
      ResetUserInfo,
      //GetUserInfo,
      LoginIn,
      LoginOut,
      setToken,
      loadingInstance,
      ClearStorage
    }
  }
)
